import { request } from "../../request/request.js"
Page({

    /**
     * 页面的初始数据
     */
    data: {
        //左侧菜单栏
        leftMenuList: [],
        rightContentList: [],
        //左侧菜单栏激活项
        currentIndex: 0,
        //页面滚动到头部
        scrollTop: 0
    },
    //分类数据
    Cates: [],
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        // 1.获取本地存储中的数据
        const Cates = wx.getStorageSync('cates')
            // 2.判断
        if (!Cates) {
            this.getCates()
        } else {
            //有旧数据  定义过期时间
            if (Date.now() - Cates.time > 1000 * 10) {
                this.getCates()
            }
            this.Cates = Cates.data;
            let leftMenuList = this.Cates.map(v => v.cat_name);
            let rightContentList = this.Cates[0].children;
            this.setData({
                leftMenuList,
                rightContentList
            })
        }
    },
    //获取分类数据
    getCates() {
        request({ url: '/categories' })
            .then(res => {
                //console.log(res)
                // 把接口数据存入到本地存储中
                this.Cates = res.data.message;
                wx.setStorageSync('cates', { time: Date.now, data: this.Cates });
                //console.log(this.Cates)
                let leftMenuList = this.Cates.map(v => v.cat_name);
                let rightContentList = this.Cates[0].children;
                this.setData({
                    leftMenuList,
                    rightContentList
                })
            })
    },
    //菜单栏点击事件
    handleItemTap(e) {
        //console.log(e)
        const { index } = e.currentTarget.dataset
        let rightContentList = this.Cates[index].children;
        this.setData({
            currentIndex: index,
            rightContentList,
            // 右侧页面滚动到头部
            scrollTop: 0
        })
    }
})